package com.lagou.module3hw.hw2;

/**
 * 编程获取两个指定字符串中的最大相同子串
 */
public class MaxSubString {

    /**
     * 获取两个指定字符串中的最大相同子串
     * @param str1 字符串1
     * @param str2 字符串2
     * @return 最大相同子串
     */
    public static String maxSubString(String str1 , String str2){
        int len1 = str1.length();
        int len2 = str2.length();

        //1.判断参数字符串是否为空，空则没有返回空
        if( len1 == 0 || len2 == 0) return "";

        //2.设置最大长度的字符串和最短长度的字符串
        String strMax = str1;
        String strMin = str2;
        if( len1 < len2){
            strMax = str2;
            strMin = str1;
        }

        //3.开始比较
        int i = 1;
        int minLen = strMin.length();
        //System.out.println(minLen);
        while( minLen > 0) {
            String str3 = strMin.substring(0,minLen);
            String str4 = strMin.substring(i,minLen-i+1);
            if (strMax.indexOf(str3) >= 0) {
                System.out.println("包含");
                return str3;
            }
            if (strMax.indexOf(str4) >= 0) {
                System.out.println("包含");
                return str4;
            }
            minLen--;
            i++;
        }

        return "";

    }
    public static void main(String[] args) {

        //1.声明两个常量字符串，他们的最大子串为"asd"
        String str1 = "asdafghjka";
        String str2 = "aaasdfg";

        //2.获取两个字符串的最大字串
        String maxSubStr = MaxSubString.maxSubString(str2,str1);
        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);
        System.out.println("他们的最大子串为:" + maxSubStr);
    }
}
